//引入fs模块
var fs = require('fs');
var path = require('path');

//封装请求文件数据的函数
function getFileData(fileName) {
  return new Promise((resolve, reject) => {
    var readStream = fs.createReadStream(fileName);
    readStream.setEncoding('UTF8');
    let data = '';
    readStream.on('data', (chunk) => (data = data + chunk));
    readStream.on('end', () => resolve(data));
    readStream.on('error', (err) => {
      console.log(err.strck);
      reject(err);
    });
  });
}

//并发请求
Promise.all([
  getFileData(path.resolve(__dirname, 'input.txt')),
  getFileData(path.resolve(__dirname, 'output.txt'))
]).then((result) => {
  var writeStream = fs.createWriteStream(path.resolve(__dirname, 'output.txt'));
  //讲两个文件的内容重新再写入到output.txt中
  console.log('result', result);
  writeStream.write(result[0] + ',' + result[1], 'UTF8');
  writeStream.end();
  //再获取output.txt文件的内容
  fs.readFile(path.resolve(__dirname, 'output.txt'), (err, content) => {
    if (err) console.log('fs.readFile-err', err);
    console.log(content.toString());
  });
});

// 'flags': 'a'在原文件内容的后面追加内容
// var fs = require('fs');
// var read = fs.createReadStream('../data/input.txt');
// //设置第二个参数append
// var write = fs.createWriteStream('../data/output.txt', { 'flags': 'a' });
// //管道流读写操作
// read.pipe(write);
// console.log('执行完毕');

// 文件追加操作
// fs.appendFile(文件名, 数据, 编码, 回调函数(err));
// var fs= require("fs");
// fs.appendFile('test.txt', 'data to append', 'utf8',function (err) {
//   if (err) throw err;   //数据被添加到文件的尾部
//     console.log('The "data to append" was appended to file!');
// });
